import 'package:dio/dio.dart';
import 'package:xin_he/service/xin_he_interceptors.dart';


class XinHeHttpRequestManager {

  /// 基础请求头-不变的放这里-动态改变的调用方法修改    authorization则根据token有无进行添加

  final Map<String, dynamic> _requestHeaders = {
    'accept' : "application/json,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    // 'client-type':'app',
  };

  /// dio对象
  final Dio _xinHeDio = Dio();
  Dio get dio => _xinHeDio;

  XinHeHttpRequestManager()  {
    setXinHeDioBaseOptionsParam();
    //cookie管理
    // dio.interceptors.add(CookieManager(CookieJar()));
    //添加请求拦截器
    dio.interceptors.add(XinHeInterceptors());
    // 忽略Https校验 非正式环境下开启
    // if (KDConfig.environmentValue != 1) {
    //   (dio.httpClientAdapter as IOHttpClientAdapter).onHttpClientCreate = (HttpClient client) {
    //     client.badCertificateCallback = (X509Certificate cert, String host, int port) {
    //       return true;
    //     };
    //     return client;
    //   };
    // }
  }

  /// 设置请求头
  ///
  /// @headers - 请求头字典
  ///
  /// @baseUrl - 接口根域名
  ///
  /// @contentType - 请求类型
  ///
  /// @responseType - 返回类型
  ///
  /// @connectTimeout - 链接超时时间 ms
  ///
  /// @receiveTimeout - 响应超时时间 ms
  Future<void> setXinHeDioBaseOptionsParam({
    Map<String, dynamic>? headers,
    String? baseUrl,
    String? contentType,
    ResponseType? responseType,
    int? connectTimeout,
    int? receiveTimeout,
  }) async {
    // 拼接基础请求头
    if (headers != null) {
      if(headers['x-access-token'] == ''){
        _requestHeaders.remove('x-access-token');
      }else {
        _requestHeaders.addAll(headers);

      }
    }

    // var loginStae = await KDLocalStorage.get(KDStorage.userLoginState);
    // //如果有登录成功设置token和uid到请求头中
    // if (loginStae != null) {
    //   if (loginStae is bool) {
    //     if (loginStae) {
    //       _requestHeaders["authorization"] =  await KDLocalStorage.get(KDStorage.accessToken);
    //       // _requestHeaders['ty91uuid'] = await KDLocalStorage.get(KDStorage.ty91uuid);
    //     }
    //   }
    // }

    dio.options = BaseOptions(
      contentType: contentType ?? "application/json;charset=UTF-8",
      responseType: responseType ?? ResponseType.plain,
      headers: _requestHeaders,
      /// 链接超时
      connectTimeout: const Duration(minutes: 10),
      /// 响应超时
      receiveTimeout: const Duration(minutes: 10),
    );
  }
}

final XinHeHttpRequestManager httpRequestManager = XinHeHttpRequestManager();